package com.ftd.lampcontrol.server.service.impl;

import java.util.List;

import com.ftd.lampcontrol.server.dao.AppUserDao;
import com.ftd.lampcontrol.server.dto.AppUserDto;
import com.ftd.lampcontrol.server.model.AppUser;
import com.ftd.lampcontrol.server.model.Group;
import com.ftd.lampcontrol.server.service.AppUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service
public class AppUserServiceImpl implements AppUserService {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	@Autowired
	private AppUserDao userDao;
	@Autowired
	private BCryptPasswordEncoder passwordEncoder;

	@Override
	@Transactional
	public AppUser saveAppUser(AppUserDto userDto) {
		AppUser user = userDto;
		user.setPassword(user.getPassword());
		log.info("新增用户AppUser:{}", user.toString());
		userDao.save(user);
		//saveUserRoles(user.getId(), userDto.getRoleIds());
		log.debug("新增用户{}", user.getUsername());
		return user;
	}

	private void saveUserRoles(Long userId, List<Long> roleIds) {
		if (roleIds != null) {
			userDao.deleteUserRole(userId);
			if (!CollectionUtils.isEmpty(roleIds)) {
				userDao.saveUserRoles(userId, roleIds);
			}
		}
	}


	@Override
	public AppUser getAppUser(String account) {
		return userDao.getUserByAccount(account);
	}

	@Override
	public void changePassword(String account, String oldPassword, String newPassword) {
		AppUser u = userDao.getUserByAccount(account);
		if (u == null) {
			throw new IllegalArgumentException("用户不存在");
		}

		if (oldPassword.equals(u.getPassword())) {
			throw new IllegalArgumentException("旧密码错误");
		}

		userDao.changePassword(u.getId(), passwordEncoder.encode(newPassword));

		log.debug("修改{}的密码", account);
	}

	@Override
	public List<Group> getGroup(Long userid) {
		return userDao.getGroupById(userid);
	}

	@Override
	public int saveGroup(Group group) {
		return userDao.saveGroup(group);
	}

	@Override
	@Transactional
	public AppUser updateAppUser(AppUserDto userDto) {
		userDao.update(userDto);
		saveUserRoles(userDto.getId(), userDto.getRoleIds());
		return userDto;
	}

}
